#include <iostream>

#include "InetAddr.hpp"
#include "talksLog.hpp"

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

talksLog talkLog;

void test(const InetAddr& aim, int sockfd)
{
    while (true)
    {
        std::string message;
        std::cout << "输入消息:";
        std::cin >> message;

        int send_ret = write(sockfd, message.c_str(), message.size());
        
        if (message == "QUIT")
        {
            return;
        }

        char buf[1024];

        int back_ret = read(sockfd, buf, sizeof(buf) - 1);
        if (back_ret > 0)
        {
            buf[back_ret] = '\0';
            std::cout << buf << std::endl;
        }
    }

    return;
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "正确格式: ./tcpClient ip port" << std::endl;
        return 1;
    }

    std::string ip = argv[1];
    int port = std::stoi(argv[2]);
    
    InetAddr serverinfo(ip, port);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    connect(sockfd, serverinfo.getAddrPtr(), serverinfo.getAddrLen());
    
    test(serverinfo, sockfd);
    
    return 0;
}